package com.ufo.store.management.ui.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.github.ybq.android.spinkit.SpinKitView;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.calendar.LunarCalendar;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.SaleDetailInfo;
import com.ufo.store.management.entity.StockInfo;
import com.ufo.store.management.ui.activity.PayMasterActivity;
import com.ufo.store.management.utils.StockComparator;
import com.ufo.store.management.widget.view.ChartMarkerView;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2015/10/4.
 */
public class CalenderFragment extends BaseLazyFragment {
    public static final String TAG = CalenderFragment.class.getSimpleName();
    private LinearLayout accounts_number_ll;
    private TextView accounts_number_tv;
    private TextView sales_statistics_tv;
    private TextView sales_champion_tv;

    private LineChart mLineChart;
    private HorizontalBarChart mHorizontalBarChart;
    private BarChart mBarChart;
    private PieChart mPieChart;

    private SpinKitView linechart_skv;
    private SpinKitView horizontalbarchart_skv;
    private SpinKitView barchart_skv;

    private LunarCalendar lc;
    private int mPosition = -1;
    private String mSearchDate = "";
    private List<HashMap<String, Object>> mSaleDetailMapList = new ArrayList<HashMap<String, Object>>();
    private StockComparator mStockComparator ;
    private CalenderClickListener mCalenderClickListener = null;

    private float fRetainedProfits = 0;   // 净利润
    private float fFirstCost = 0;         // 成本
    private float fUnknown = 0;           // 未计算（无法统计）

    /**
     * 布局文件ID
     *
     * @return
     */
    protected int getLayoutId() {
        return R.layout.fragment_calender;
    }


    /**
     * 初始化数据
     */
    protected void initData() {
        loaded();
        mStockComparator = new StockComparator();
    }

    protected void onFirstUserVisible() {
        new GetSaleDetailsInfoTask().execute();
    }

    protected void onUserVisible() {

    }

    protected void onFirstUserInvisible() {

    }

    protected void onUserInvisible() {

    }

    /**
     * 初始化组件
     */
    protected void initViewData(View EntryView) {
        accounts_number_tv = (TextView) EntryView.findViewById(R.id.accounts_number_tv);
        sales_statistics_tv = (TextView) EntryView.findViewById(R.id.sales_statistics_tv);
        sales_champion_tv = (TextView) EntryView.findViewById(R.id.sales_champion_tv);
        accounts_number_ll = (LinearLayout) EntryView.findViewById(R.id.accounts_number_ll);
        accounts_number_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( mCalenderClickListener != null ){
                    mCalenderClickListener.onAccountsNumberClick();
                }
            }
        });

        linechart_skv = (SpinKitView) EntryView.findViewById(R.id.linechart_skv);
        horizontalbarchart_skv = (SpinKitView) EntryView.findViewById(R.id.horizontalbarchart_skv);
        barchart_skv = (SpinKitView) EntryView.findViewById(R.id.barchart_skv);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, mPosition - (PayMasterActivity.CALENDER_DAY_COUNT - 1));

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        mSearchDate = sDateFormat.format(cal.getTime());
        //mSearchDate = year + "-" + month + "-" + day;

//        int way = cal.get(Calendar.DAY_OF_WEEK);
//        String mWay = null;
//        if (way == 1) {
//            mWay = "天";
//        } else if (way == 2) {
//            mWay = "一";
//        } else if (way == 3) {
//            mWay = "二";
//        } else if (way == 4) {
//            mWay = "三";
//        } else if (way == 5) {
//            mWay = "四";
//        } else if (way == 6) {
//            mWay = "五";
//        } else if (way == 7) {
//            mWay = "六";
//        }
//        String s = year + "年" + month + "月" + day + "号";
//        mCalenderWayTv1.setText(s);
//        mCalenderWayTv.setText( " 星期" + mWay );
//        lc = new LunarCalendar();
//        String lunarDay = lc.getLunarDate(year, month, day ,false);
//        mLcCalenderDayTv.setText(lunarDay);

        mLineChart = (LineChart) EntryView.findViewById(R.id.linechart);
        setLineChart();
        mHorizontalBarChart = (HorizontalBarChart) EntryView.findViewById(R.id.horizontalbarchart);
        setHorizontalBarChart();
//        mBarChart = (BarChart) EntryView.findViewById(R.id.barchart);
//        setBarChart();
        mPieChart = (PieChart) EntryView.findViewById(R.id.piechart);
        setPieChart();
    }

    private void setLineChart() {
        mLineChart.getDescription().setText("");
        mLineChart.setNoDataText("没有成交记录");//没有数据时显示的文字
        mLineChart.setNoDataTextColor(R.color.app_key_color);//没有数据时显示文字的颜色
        // enable touch gestures
        mLineChart.setTouchEnabled(true);

        // enable scaling and dragging
        mLineChart.setDragEnabled(true);    // 可以拖动
        mLineChart.setScaleEnabled(false);
        mLineChart.setScaleXEnabled(true);  //x方向可以缩放
        mLineChart.setScaleYEnabled(false); //y方向不可以缩放

        // if disabled, scaling can be done on x- and y-axis separately
        mLineChart.setPinchZoom(true);

        // set an alternative background color
        // mLineChart.setBackgroundColor(Color.GRAY);

        //左侧纵坐标
        YAxis leftAxis = mLineChart.getAxisLeft();
        leftAxis.setEnabled(true);
//        leftAxis.removeAllLimitLines();
//        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setDrawGridLines(false);       //中部横线
 //       leftAxis.setGridLineWidth(0.3f);
        leftAxis.setTextSize(10f);
//        leftAxis.setGridColor(Color.WHITE);
//        leftAxis.setGranularityEnabled(true);
//        leftAxis.setYOffset(-5f);
        leftAxis.setTextColor(Color.parseColor("#5c5c5c"));
        //   leftAxis.setAxisMaxValue(220f);
        //leftAxis.setAxisMinValue(0f);
        //leftAxis.setYOffset(20f);
        //leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(true);
        // limit lines are drawn behind data (and not on top)
        leftAxis.setDrawLimitLinesBehindData(true);
        // interval 1
        leftAxis.setGranularity(1f);
        leftAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int)(value)) + "笔";
            }
        });

        //右侧纵坐标(同左侧纵坐标)
        mLineChart.getAxisRight().setEnabled(false);
        mLineChart.getAxisRight().setDrawAxisLine(false);
        mLineChart.getAxisRight().setDrawGridLines(false);

        //底部横坐标
        XAxis xAxis = mLineChart.getXAxis();
        //xAxis.setValueFormatter(new MyCustomXAxisValueFormatter());
        //xAxis.addLimitLine(llXAxis); // add x-axis limit line
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextSize(10f);
        xAxis.setTextColor(Color.parseColor("#5c5c5c"));    //底部横坐标的颜色
        xAxis.setDrawAxisLine(true);           //横线网格
        xAxis.setDrawGridLines(false);          //竖线网格
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int)value) + ":00";
            }
        });

        //mLineChart.getViewPortHandler().setMaximumScaleY(2f);
        //mLineChart.getViewPortHandler().setMaximumScaleX(2f);

//        mLineChart.setVisibleXRange(20);
//        mLineChart.setVisibleYRange(20f, AxisDependency.LEFT);
//        mLineChart.centerViewTo(20, 50, AxisDependency.LEFT);

        //底部说明文字
        Legend l = mLineChart.getLegend();
        l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);        //底部说明文字位置
        l.setForm(Legend.LegendForm.CIRCLE);                            //底部说明文字前面是显示圆圈还是其他
        l.setTextColor(Color.parseColor("#5c5c5c"));        //底部说明文字颜色

        // mLineChart.invalidate();

        ChartMarkerView mv = new ChartMarkerView(getActivity(), R.layout.layout_chart_marker_view);
        mLineChart.setMarker(mv);
    }

    private void setLineChartData(ArrayList<String> hourValueList, ArrayList<String> scanValueList) {
        int count = scanValueList.size();
        if( count == 0 )
            return;
        ArrayList<Entry> yVals = new ArrayList<Entry>();
        for (int i = 0; i < count; i++) {
            float time = Float.parseFloat(((String) hourValueList.get(i)));
            float value = Float.parseFloat(((String) scanValueList.get(i)));
            yVals.add(new Entry(time, value));
        }

        //底部横坐标，坐标显示个数
        XAxis xAxis = mLineChart.getXAxis();
        xAxis.setLabelCount(count, true);

//        Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
//        //---------基准线-------------
//        LimitLine ll2 = new LimitLine(fmaxValue, "");
//        ll2.setLineWidth(0.5f);
//        ll2.enableDashedLine(10f, 10f, 0f);
//        ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
//        ll2.setTextSize(10f);
//        ll2.setTypeface(tf);
//        LimitLine ll3 = new LimitLine(fminValue, "");
//        ll3.setLineWidth(0.5f);
//        ll3.enableDashedLine(10f, 10f, 0f);
//        ll3.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
//        ll3.setTextSize(10f);
//        ll3.setTypeface(tf);
//        //---------添加基准线-------------
//        YAxis leftAxis = mChart.getAxisLeft();
//        leftAxis.removeAllLimitLines();
//        leftAxis.addLimitLine(ll2);
//        leftAxis.addLimitLine(ll3);

        LineDataSet set1 = new LineDataSet(yVals, "不同时段成交量（笔）");
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);   //折线/弧度
        set1.setDrawCircles(false);
        set1.setLineWidth(2f);
        set1.setCircleRadius(8f);                                                   //折线上圆的半径
        set1.setColor(getResources().getColor(R.color.app_key_color));              //折线的颜色
        set1.setCircleColor(getResources().getColor(R.color.white));                //折线上圆的颜色
        set1.setDrawCircleHole(true);                                                //是否在圆中间再画一个小圆
        set1.setCircleColorHole(getResources().getColor(R.color.app_key_color));     //圆中间再画的小圆什么颜色

        //set1.setDrawFilled(true);                             // 设置允许填充
        //set1.setFillColor(Color.parseColor("#ff8c9d"));

        set1.setDrawValues(false);                              //折线上的文字
        set1.setValueTextSize(10f);
        set1.setValueTextColor(Color.parseColor("#5c5c5c"));   //折线上文字的颜色

//        set1.enableDashedHighlightLine(10f, 5f, 0f);//点击后的高亮线的显示样式
//        set1.setHighlightLineWidth(2f);//设置点击交点后显示高亮线宽
//        set1.setHighlightEnabled(true);//是否禁用点击高亮线
//        set1.setHighLightColor(Color.RED);//设置点击交点后显示交高亮线的颜色

        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        dataSets.add(set1);
        LineData data = new LineData(dataSets);
        Typeface mTf = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");
        data.setValueTypeface(mTf);

        mLineChart.setVisibility(View.VISIBLE);
        mLineChart.setData(data);
        mLineChart.animateY(1400, Easing.EasingOption.EaseInOutQuart);
    }

    private void setHorizontalBarChart() {
        mHorizontalBarChart.getDescription().setText("");
        mHorizontalBarChart.setNoDataText("没有营收记录");//没有数据时显示的文字
        mHorizontalBarChart.setNoDataTextColor(R.color.app_key_color);//没有数据时显示文字的颜色
        mHorizontalBarChart.setDrawBarShadow(false);

        mHorizontalBarChart.setDrawValueAboveBar(true);

        // enable touch gestures
        mHorizontalBarChart.setTouchEnabled(true);

        // enable scaling and dragging
        mHorizontalBarChart.setDragEnabled(false);    // 不可以拖动
        mHorizontalBarChart.setScaleEnabled(false);
        mHorizontalBarChart.setScaleXEnabled(false);  //x方向不可以缩放
        mHorizontalBarChart.setScaleYEnabled(false); //y方向不可以缩放

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mHorizontalBarChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        mHorizontalBarChart.setPinchZoom(false);

        // draw shadows for each bar that show the maximum value
        // mChart.setDrawBarShadow(true);

        // mChart.setDrawXLabels(false);

        mHorizontalBarChart.setDrawGridBackground(false);

        // mChart.setDrawYLabels(false);

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");

        //左侧纵坐标
        XAxis xl = mHorizontalBarChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setTypeface(tf);
        xl.setDrawAxisLine(false);
        xl.setDrawGridLines(false);
        xl.setGridLineWidth(0.3f);
        xl.setTextColor(Color.parseColor("#5c5c5c"));    //左侧纵坐标的颜色
        xl.setTextSize(10f);
        xl.setGranularity(1);
        xl.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String str = "";
                if( value == 0 ){
                    str = "未计算";
                }else if( value == 1 ){
                    str = "成本";
                }else if( value == 2 ){
                    str = "净利润";
                }
                return str;
            }
        });

        //上部横坐标
        YAxis yl = mHorizontalBarChart.getAxisLeft();
        yl.setEnabled(false);
        yl.setTypeface(tf);
        yl.setDrawAxisLine(false);           //横线网格
        yl.setDrawGridLines(false);          //竖线网格
        yl.setGridLineWidth(0.3f);
        yl.setAxisMinValue(0f); // this replaces setStartAtZero(true)
        yl.setTextColor(Color.parseColor("#ff5c5c"));
        yl.setTextSize(10f);
//        yl.setInverted(true);

        //底部横坐标
        YAxis yr = mHorizontalBarChart.getAxisRight();
        yr.setEnabled(true);
        yr.setTypeface(tf);
        yr.setDrawAxisLine(false);           //横线网格
        yr.setDrawGridLines(false);          //竖线网格
        yr.setGridLineWidth(0.3f);
        yr.setAxisMinValue(0f); // this replaces setStartAtZero(true)
        yr.setTextColor(Color.parseColor("#5c5c5c"));
        yr.setTextSize(10f);
        yr.setValueFormatter(new MyBarChartYAxisValueValueFormatter());

        //底部说明文字
        Legend l = mHorizontalBarChart.getLegend();
        l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        l.setForm(Legend.LegendForm.LINE);
        l.setTextColor(Color.parseColor("#5c5c5c"));        //底部说明文字颜色
//        l.setFormSize(8f);
//        l.setXEntrySpace(4f);

        mHorizontalBarChart.animateY(2500);
    }

    private void setHorizontalBarChartData() {
        if( fUnknown == 0 && fFirstCost == 0 && fRetainedProfits == 0 )
            return;
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        yVals1.add(new BarEntry(0, fUnknown));
        yVals1.add(new BarEntry(1, fFirstCost));
        yVals1.add(new BarEntry(2, fRetainedProfits));

        //不同矩形条的颜色
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(Color.parseColor("#ef0505"));
        colors.add(Color.parseColor("#f23030"));
        colors.add(Color.parseColor("#f15e5e"));

        BarDataSet set1 = new BarDataSet(yVals1, "销售额(元)");
        set1.setColors(colors);
        set1.setDrawValues(true);                                       //折线上的文字
        set1.setValueFormatter(new MyHorizontalBarChartYValueValueFormatter());
        set1.setValueTextSize(10f);
        set1.setValueTextColor(Color.parseColor("#5c5c5c"));   //柱状图上文字颜色

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");
        BarData data = new BarData(dataSets);
        data.setValueTextSize(10f);
        data.setValueTypeface(tf);
        data.setBarWidth(0.9f);

        mHorizontalBarChart.setData(data);
        mHorizontalBarChart.animateY(2500);
    }

    private class MyHorizontalBarChartYValueValueFormatter implements IValueFormatter {
        public MyHorizontalBarChartYValueValueFormatter() {
        }

        @Override
        public String getFormattedValue(float var1, Entry var2, int var3, ViewPortHandler var4) {
            DecimalFormat decimalFormat = new DecimalFormat("##,###.0");
            return "¥" + decimalFormat.format(var1);
        }
    }

    private void setBarChart() {
        mBarChart.getDescription().setText("");
        mBarChart.setDrawBarShadow(false);
        mBarChart.setDrawValueAboveBar(true);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mBarChart.setMaxVisibleValueCount(10);

        // scaling can now only be done on x- and y-axis separately
        mBarChart.setPinchZoom(false);

        mBarChart.setDrawGridBackground(false);
        // mChart.setDrawYLabels(false);

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");

        XAxis xAxis = mBarChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTypeface(tf);
        xAxis.setDrawGridLines(false);
        xAxis.setTextColor(Color.parseColor("#5c5c5c"));
        xAxis.setTextSize(10f);

        MyBarChartYAxisValueValueFormatter custom = new MyBarChartYAxisValueValueFormatter();

        YAxis leftAxis = mBarChart.getAxisLeft();
        leftAxis.setEnabled(true);
        leftAxis.setTypeface(tf);
        leftAxis.setLabelCount(8, false);
        //leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)
        leftAxis.setTextColor(Color.parseColor("#5c5c5c"));

        YAxis rightAxis = mBarChart.getAxisRight();
        rightAxis.setEnabled(false);
        rightAxis.setDrawGridLines(false);
        rightAxis.setTypeface(tf);
        rightAxis.setLabelCount(8, false);
        //rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        rightAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)
        rightAxis.setTextColor(Color.parseColor("#5c5c5c"));

        //底部说明文字
        Legend l = mBarChart.getLegend();
        l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(10f);
        l.setXEntrySpace(4f);
        l.setTextColor(Color.parseColor("#5c5c5c"));
    }

    private void setBarChartData() {
        ArrayList<String> xVals = new ArrayList<String>();
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        if (mSaleDetailMapList.size() > 0) {
            for (int i = 0; i < mSaleDetailMapList.size(); i++) {
                HashMap<String, Object> itemCopy = mSaleDetailMapList.get(i);
                String stockTotal = ((String) itemCopy.get("total")).trim();
                String stockName = ((String) itemCopy.get("name")).trim();
                yVals1.add(new BarEntry(Float.parseFloat(stockTotal), i));
                xVals.add(stockName);
            }
        } else {
            return;
        }

        BarDataSet set1 = new BarDataSet(yVals1, "今日销量前" + BarApplication.getInstance().mStatisticsStockNumber + "名");
        set1.setValueTextColor(Color.parseColor("#5c5c5c"));   //柱状图上文字颜色
        set1.setValueFormatter(new MyHorizontalBarChartYValueValueFormatter());
        set1.setColor(Color.parseColor("#f23030"));                 //柱状图颜色

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");
        BarData data = new BarData(dataSets);
        data.setValueTextSize(10f);
        data.setValueTypeface(tf);

        mBarChart.setData(data);
        mBarChart.animateY(3000);
    }

    private class MyBarChartYAxisValueValueFormatter implements IAxisValueFormatter {
        public MyBarChartYAxisValueValueFormatter() {
        }

        @Override
        public String getFormattedValue(float value, AxisBase yAxis) {
            DecimalFormat decimalFormat = new DecimalFormat("##,###.0");
            return "¥" + decimalFormat.format(value);
        }
    }

    private void setPieChart(){
        mPieChart.getDescription().setText("");
        mPieChart.setExtraOffsets(5, 10, 5, 5);
        mPieChart.setNoDataText("没有销售记录");//没有数据时显示的文字
        mPieChart.setNoDataTextColor(R.color.app_key_color);//没有数据时显示文字的颜色

        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        if( BarApplication.getInstance().mbStockDisplayInnerCircle) {    //是否显示中间圆
            mPieChart.setDrawHoleEnabled(true);
            mPieChart.setCenterTextTypeface(Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Light.ttf"));
        }
        else
            mPieChart.setDrawHoleEnabled(false);

        mPieChart.setHoleColor(Color.WHITE);
        mPieChart.setTransparentCircleColor(Color.WHITE);
        mPieChart.setTransparentCircleAlpha(110);
        mPieChart.setBackgroundColor(Color.WHITE);

        //mPieChart.setHoleRadius(0); //实心圆 
        mPieChart.setHoleRadius(48f);//半径
        mPieChart.setTransparentCircleRadius(51f);

        mPieChart.setDrawCenterText(true);

        mPieChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        mPieChart.setRotationEnabled(true);        // 可以手动旋转  

        mPieChart.setHighlightPerTapEnabled(true);
        mPieChart.setUsePercentValues(false);//设置不显示成比例  
        mPieChart.setEntryLabelColor(Color.parseColor("#5c5c5c"));   //label文字的颜色

        //mPieChart.setDrawSliceText(false); //设置隐藏饼图上文字，只显示百分比  

        //底部说明文字
        Legend l = mPieChart.getLegend();
        //l.setPosition(Legend.LegendPosition.LEFT_OF_CHART_CENTER);
        l.setWordWrapEnabled(true);
        l.setTextSize(10f);
        l.setXEntrySpace(4f);
        l.setTextColor(Color.parseColor("#5c5c5c"));
//        l.setXEntrySpace(200f);
//        l.setYEntrySpace(0f);
//        l.setYOffset(0f);
//        l.setXOffset(0f);
    }

    private void setPieChartData() {
        ArrayList<PieEntry> yVals1 = new ArrayList<PieEntry>();
        if(mSaleDetailMapList.size()>0){
            for (int i = 0; i < mSaleDetailMapList.size(); i++) {
                HashMap<String, Object> itemCopy = mSaleDetailMapList.get(i);
                String stockTotal = ((String) itemCopy.get("total")).trim();
                String stockName = ((String) itemCopy.get("name")).trim();
                yVals1.add(new PieEntry(Float.parseFloat(stockTotal), stockName));
            }
        }else{
            return;
        }

        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(Color.parseColor("#f23030"));
        colors.add(Color.parseColor("#f03f3f"));
        colors.add(Color.parseColor("#ef4d4d"));
        colors.add(Color.parseColor("#ee5e5e"));
        colors.add(Color.parseColor("#ec6f6f"));
        colors.add(Color.parseColor("#ec8282"));

        PieDataSet dataSet = new PieDataSet(yVals1, "今日销量前" + BarApplication.getInstance().mStatisticsStockNumber + "名");
        dataSet.setValueTextColor(Color.parseColor("#ffffff"));   //柱状图上文字颜色
        dataSet.setValueFormatter(new MyPieChartYValueValueFormatter());
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);
        dataSet.setColors(colors);       //柱状图颜色

        dataSet.setValueLinePart1OffsetPercentage(80.f);   //延申出去的线
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        //dataSet.setUsingSliceColorAsValueLineColor(true);
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        //dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");
        PieData data = new PieData(dataSet);
        data.setValueTextSize(10f);
        data.setValueTypeface(tf);

        mPieChart.setData(data);
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuart);
    }

    private class MyPieChartYValueValueFormatter implements IValueFormatter {
        public MyPieChartYValueValueFormatter () {
        }

        @Override
        public String getFormattedValue(float var1, Entry var2, int var3, ViewPortHandler var4) {
            DecimalFormat decimalFormat = new DecimalFormat("##,###.0");
            return "¥" + decimalFormat.format(var1);
        }
    }

    public void setRefresh() {
        new GetSaleDetailsInfoTask().execute();
    }

    public void setPosition(int position) {
        mPosition = position;
    }

    public void setAccountsNumber(String accountsNum, ArrayList<String> hourValueList, ArrayList<String> scanValueList) {
        if( linechart_skv != null )
            linechart_skv.setVisibility(View.GONE);
        if( accounts_number_tv != null )
            accounts_number_tv.setText(accountsNum);
        if( mLineChart != null ) {
            mLineChart.setVisibility(View.VISIBLE);
            setLineChartData(hourValueList, scanValueList);
        }
    }

    private class GetSaleDetailsInfoTask extends AsyncTask<Void, Void, List<List<HashMap<String, Object>>>> {
        public GetSaleDetailsInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mPieChart.setVisibility(View.GONE);
            mHorizontalBarChart.setVisibility(View.GONE);
            horizontalbarchart_skv.setVisibility(View.VISIBLE);
            barchart_skv.setVisibility(View.VISIBLE);
            fRetainedProfits = 0;   // 净利润
            fFirstCost = 0;         // 成本
            fUnknown = 0;           // 未计算（无法统计）
        }

        @Override
        protected List<List<HashMap<String, Object>>> doInBackground(Void... params) {
            List<SaleDetailInfo> saleDetailList = new ArrayList<>();
            if (BarApplication.getInstance().mDatabaseIsSqlServer)
                saleDetailList = DatabaseManager.getSaleDetailInfoFromSqlServer(getContext(), 1, mSearchDate);
            else
                saleDetailList = DatabaseManager.getSaleDetailInfoFromLocal(getContext(), 1, mSearchDate);
            mSaleDetailMapList.clear();
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            for (SaleDetailInfo saleDetailInfo : saleDetailList) {
                // 统计收益情况
                if (saleDetailInfo.saleDetailCost != 0) {
                    fRetainedProfits = fRetainedProfits + (saleDetailInfo.saleDetailPrice - saleDetailInfo.saleDetailCost) * saleDetailInfo.saleDetailQuantity;
                    fFirstCost = fFirstCost + saleDetailInfo.saleDetailCost * saleDetailInfo.saleDetailQuantity;
                } else {
                    fUnknown = fUnknown + saleDetailInfo.saleDetailPrice * saleDetailInfo.saleDetailQuantity;
                }

                boolean bFindStock = false;
                HashMap<String, Object> mapFind = null;
                for (HashMap<String, Object> map : mSaleDetailMapList) {
                    if (map.get("name").equals(saleDetailInfo.saleDetailStockid)) {
                        bFindStock = true;
                        mapFind = map;
                        break;
                    }
                }
                if (bFindStock && mapFind != null) {
                    //已经统计过该商品了
                    float quantity = Float.valueOf((String) mapFind.get("quantity")) + saleDetailInfo.saleDetailQuantity;
                    float total = Float.valueOf((String) mapFind.get("total")) + saleDetailInfo.saleDetailQuantity * saleDetailInfo.saleDetailPrice;
                    mapFind.remove("quantity");
                    mapFind.remove("total");
                    mapFind.put("quantity", decimalFormat.format(quantity));
                    mapFind.put("total", decimalFormat.format(total));
                } else {
                    //还没有统计该商品，直接加入列表中
                    HashMap<String, Object> itemCopy = new HashMap<String, Object>();
                    itemCopy.put("name", saleDetailInfo.saleDetailStockid);
                    itemCopy.put("quantity", decimalFormat.format(saleDetailInfo.saleDetailQuantity));
                    itemCopy.put("price", decimalFormat.format(saleDetailInfo.saleDetailPrice));
                    itemCopy.put("total", decimalFormat.format(saleDetailInfo.saleDetailQuantity * saleDetailInfo.saleDetailPrice));
                    mSaleDetailMapList.add(itemCopy);
                }
            }

            // 排序
            Collections.sort(mSaleDetailMapList, mStockComparator);

            // 解析中文名
            int count = 0;
            Iterator<HashMap<String, Object>> it = mSaleDetailMapList.iterator();
            while (it.hasNext()) {
                HashMap<String, Object> value = it.next();
                if (count < BarApplication.getInstance().mStatisticsStockNumber) {
                    String stockId = ((String) value.get("name")).trim();
                    List<StockInfo> result = new ArrayList<>();
                    if (BarApplication.getInstance().mDatabaseIsSqlServer)
                        result = DatabaseManager.getStockInfoListFromSqlServer(getActivity(), 0, -1, -1, 5, -1, stockId);
                    else
                        result = DatabaseManager.getStockInfoListFromLocal(getActivity(), 0, -1, 5, -1, stockId);
                    if (result != null && result.size() != 0) {
                        value.put("name", result.get(0).stockName);
                    }
                } else {
                    it.remove();
                }
                count++;
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, Object>>> result) {
            super.onPostExecute(result);
            if( getActivity() != null && !getActivity().isFinishing()) {
                DecimalFormat decimalFormat = new DecimalFormat("##,###.0");
                sales_statistics_tv.setText(decimalFormat.format(fRetainedProfits));
                if( mSaleDetailMapList!=null && mSaleDetailMapList.size() != 0 )
                    sales_champion_tv.setText((String)mSaleDetailMapList.get(0).get("name"));
                mPieChart.setVisibility(View.VISIBLE);
                mHorizontalBarChart.setVisibility(View.VISIBLE);
                horizontalbarchart_skv.setVisibility(View.GONE);
                barchart_skv.setVisibility(View.GONE);
                setHorizontalBarChartData();
                setPieChartData();
                //setBarChartData();
            }
        }
    }

    public void setCalenderClickListener(CalenderClickListener listener) {
        mCalenderClickListener = listener;
    }

    public interface CalenderClickListener {
        void onAccountsNumberClick();
    }
}
